package cn.com.tianpeidong.restaurantadmin.project.admin.user.service.impl;

import java.util.Set;

import cn.com.tianpeidong.restaurantadmin.common.util.security.ShiroUtils;
import cn.com.tianpeidong.restaurantadmin.project.admin.menu.mapper.MenuMapper;
import cn.com.tianpeidong.restaurantadmin.project.admin.menu.mapper.PermissionMapper;
import com.alibaba.fastjson.JSONObject;

import org.apache.shiro.authz.UnauthenticatedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.tianpeidong.restaurantadmin.project.admin.user.mapper.UserInfoMapper;
import cn.com.tianpeidong.restaurantadmin.project.admin.user.service.IPermissionService;

import static cn.com.tianpeidong.restaurantadmin.common.web.constant.ProjectConstant.DEFAULT_ADMIN_ID;

@Service
public class PermissionServiceImpl implements IPermissionService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public JSONObject listUserPerms() {
        Long userId = 1L;
        try {
            userId = ShiroUtils.getUserId();
        } catch (NullPointerException ex) {
            throw new UnauthenticatedException();
        }

        Set<String> menuCodeList = null;
        Set<String> permsList = null;

        String roleName = userInfoMapper.getUserRole(userId);

        JSONObject infoMap = new JSONObject();

        menuCodeList = userId.equals(DEFAULT_ADMIN_ID) ?
                menuMapper.listAllMenuCode() : userInfoMapper.listUserMenu(userId);
        permsList = userId.equals(DEFAULT_ADMIN_ID) ?
                permissionMapper.listAllPermCode() : userInfoMapper.listUserPerm(userId);


        infoMap.put("userId", ShiroUtils.getUserId());
        infoMap.put("userName", ShiroUtils.getSysUser().getUserName());

        infoMap.put("roleName", roleName);
        infoMap.put("menuList", menuCodeList);
        infoMap.put("permissionList", permsList);
        return infoMap;
    }

}